package datastructure;
import java.util.ArrayList;


public class Alternative {
	private ArrayList<Term> terms;
	
	public Alternative() {
		terms = new ArrayList<Term>();
	}
	
	public Alternative(ArrayList<Term> terms) {
		this.terms = terms;
	}
	
	public void addToTerms(Term term) {
		terms.add(term);
	}
	
	public String toString() {
		String s = "";
		for(Term t : terms) {
			s += t.toString() + " ";
		}
		return s;
	}
	
	public boolean isEmpty(){
		return terms.size() == 1 && terms.contains(new Term("E"));
	}
	
	public Term getFirstTerm() {
		return terms.get(0);
	}
	
	public Term getTerm(int index) {
		Term toReturn = null;
		try {
			toReturn = terms.get(index);
		} catch(IndexOutOfBoundsException oob) {
			toReturn = null;
		}
		return toReturn;
	}

	public ArrayList<Term> getTerms() {
		return terms;
	}

	public void defineStarters(Rule toAdd) {
		for (Term currentTerm: terms) {
			if(currentTerm instanceof Terminal) {
				toAdd.addToStarters(currentTerm);
				break;
			} else {
				Rule rule = Grammatica.getInstance().findRuleByTerm((NonTerminal)currentTerm);
				ArrayList<Term> tempStarters = rule.defineStarters();
				toAdd.addToStarters(tempStarters);
				Terminal empty = new Terminal("E");
				if(!tempStarters.contains(empty)) {
					break;
				}
			}
		}
	}
}
